var redis = require("redis")
var monthCardCfg = require("../conf/monthCard.json")
var giftBagCfg = require("../conf/giftBag.json")
var hostCfg = require("../conf/host.json")
var util = require("../util/util.js")
var backstageMessageLogger = require("pomelo-logger").getLogger("backstageMessage-log");
var handler = module.exports
var RDS_PORT = 6379
var RDS_HOST = hostCfg.cacheDB
var RDS_PWD = hostCfg.cachePassword
var RDS_OPTS = {auth_pass : RDS_PWD}
var local = {}
var db = {}
var dbService = {}
handler.start = function(myDbServer) {
	db = redis.createClient(RDS_PORT,RDS_HOST,RDS_OPTS)
	db.on("ready",function(res) {
		db.select("15",function(err) {
			myDbServer.cacheDB = db
			dbService = myDbServer
			setTimeout(local.disposeMessage,5000)
		})
	})
}
//接受指令
local.disposeMessage = function() {
	db.blpop("backstageMessage",1,function(err,response){
		if(response && response[1]){
			backstageMessageLogger.info(response[1])
			local.dispenseMessage(response[1])
		}
		local.disposeMessage()
	});
}
//处理指令
local.dispenseMessage = function(info) {
	info = JSON.parse(info)
	info.dispenseTime = (new Date()).getTime()
	switch(info.type){
		case "addGold" :
			//增加金币
			if(info.uid && info.value && typeof(info.uid) === "number" && typeof(info.value) === "number"){
				dbService.addItemReason(info.uid,102,info.value,"后台",function(flag) {
					local.messageFinish(info,flag)
				})
			}else{
				local.messageFinish(info,false,"argumentsError")
			}
		break
		case "addDiamond" :
			//增加钻石
			if(info.uid && info.value && typeof(info.uid) === "number" && typeof(info.value) === "number"){
				dbService.addItemReason(info.uid,101,info.value,"后台",function(flag) {
					local.messageFinish(info,flag)
				})
			}else{
				local.messageFinish(info,false,"argumentsError")
			}
		break
		case "addLottryCount" :
			//增加抽奖次数
			if(info.uid && info.value && typeof(info.uid) === "number" && typeof(info.value) === "number"){
				dbService.addItemReason(info.uid,201,info.value,"后台",function(flag) {
					local.messageFinish(info,flag)
				})
			}else{
				local.messageFinish(info,false,"argumentsError")
			}
		break
		case "addItem" :
			//增加道具
			if(info.itemId && info.uid && info.value 
				&& typeof(info.uid) === "number" && typeof(info.value) === "number" && typeof(info.itemId) == "number"){
				dbService.addItemReason(info.uid,info.itemId,info.value,"后台",function(flag) {
					local.messageFinish(info,flag)
				})
			}else{
				local.messageFinish(info,false,"argumentsError")
			}
		break
		case "sendMail" :
			//发送邮件
			if(typeof(info.uid) !== "number"|| typeof(info.title) !== "string" || typeof(info.content) !== "string" || (info.award && typeof(info.award) !== "object")){
				local.messageFinish(info,false,"argumentsError")
				return
			}
			dbService.app.rpc.db.mail.sendMail(null,info.uid,info.title,info.content,info.award,function(flag) {
				local.messageFinish(info,flag)
			})
		break
		case "getUserInfo" :
			//获取玩家完整信息
			if(typeof(info.uid) !== "number"){
				local.messageFinish(info,false,"argumentsError")
				return
			}
			info.respond = true
			dbService.getPlayerInfoByUid(info.uid,function(data) {
				if(data){
				    info.userInfo = data
				    info.time = (new Date()).getTime()
				    local.messageFinish(info,true)
				}else{
					local.messageFinish(info,false,"userInfoError")
				}
			})
		break
		case "setFreeze" :
			var state = info.state
			var uid = info.uid
			if(!uid){
				local.messageFinish(info,false,"argumentsError")
				return
			}
			if(state == 1){
				dbService.setPlayer(uid,"freeze",1,function(){
					local.messageFinish(info,true)
				})
			}else{
				dbService.setPlayer(uid,"freeze",0,function(){
					local.messageFinish(info,true)
				})
			}
		break
		case "withdrawal":
			//提现
			var state = info.state
			var uid = info.uid
			if(!uid){
				local.messageFinish(info,false,"argumentsError")
				return
			}
			if(state == 1){
				dbService.app.rpc.db.withdrawal.applySuccess(null,uid,function(flag,err){
					local.messageFinish(info,flag,err)
				})
			}else{
				dbService.app.rpc.db.withdrawal.applyReject(null,uid,function(flag,err){
					local.messageFinish(info,flag,err)
				})
			}
		break
		case "recharge":
			//充值
			if(info.uid && info.rmb && info.diamond && typeof(info.uid) === "number" && typeof(info.rmb) === "number" 
				&& typeof(info.diamond) === "number"){
				//增加钻石
				dbService.addItemReason(info.uid,101,info.diamond,"充值",function(flag) {
					dbService.app.rpc.db.task.updateTask(null,info.uid,"recharge",info.rmb,null)
					var notify = {
						cmd : "recharge",
						rmb : info.rmb,
						diamond : info.diamond
					}
					dbService.app.rpc.game.remote.sendByUid(null,info.uid,notify,function(){})
					dbService.app.rpc.db.inviter.inviterBrokerage(null,info.uid,info.rmb,null)
					local.messageFinish(info,flag)
				})
			}else{
				local.messageFinish(info,false,"argumentsError")
			}
		break
		case "buyMonthCard":
			//购买月卡
			var uid = info.uid
			var monthCardType = info.monthCardType
			if(monthCardType && monthCardCfg[monthCardType]){
				var immediately = monthCardCfg[monthCardType].immediately
				dbService.db.hget("game:monthCard:"+uid,monthCardType,function(err,data) {
					var tmpDate = new Date()
					tmpDate.setHours(0)
					tmpDate.setMinutes(0)
					tmpDate.setSeconds(0)
					tmpDate.setMilliseconds(0)
					var value = tmpDate.getTime()
					if(!err && data){
						if(data > value){
							value = data
						}
					}
					value = parseInt(value)
					value += 31 * 24 * 60 * 60 * 1000
					dbService.db.hset("game:monthCard:"+uid,monthCardType,value,function(){
						var notify = {
							cmd : "buyMonthCard",
							monthCardType : monthCardType,
							endTime : value
						}
						dbService.app.rpc.game.remote.sendByUid(null,uid,notify,function(){})
						info.endTime = value
						local.messageFinish(info,true)
					})
				})
				//增加记牌器时长
				dbService.db.hget("NoAdTimeList",uid,function(err,data) {
					var value = (new Date()).getTime()
					if(!err && data){
						if(data > value){
							value = data
						}
					}
					value = parseInt(value)
					value += 31 * 24 * 60 * 60 * 1000
					dbService.db.hset("NoAdTimeList",uid,value)
				})
				//购买奖励邮件
				dbService.app.rpc.db.mail.sendMail(null,uid,monthCardCfg[monthCardType].name,"您购买"+monthCardCfg[monthCardType].name+"获得以下奖励，祝您玩的开心！",immediately,function() {})
				//充值任务
				dbService.app.rpc.db.task.updateTask(null,info.uid,"recharge",monthCardCfg[monthCardType].price,null)
			}else{
				local.messageFinish(info,false,"argumentsError")
			}
		break
		case "buyGiftBag":
			//购买礼包
			var uid = info.uid
			var giftType = info.giftType
			var level = info.level
			var curDate = util.getDateString()
			if(giftBagCfg[giftType] && giftBagCfg[giftType][level]){
				if(giftType == "dayGift"){
					//每日礼包
					dbService.db.hget("game:giftBag:"+uid,giftType+":"+level,function(err,data) {
						if(err || !data || data < curDate){
							var notify = {
								cmd : "buyGiftBag",
								giftType : giftType,
								level : level
							}
							dbService.app.rpc.game.remote.sendByUid(null,uid,notify,function(){})
							//购买记录
							dbService.db.hincrby("game:giftBag:"+uid,giftType+":"+level+":count",1)
							//时间记录
							dbService.db.hset("game:giftBag:"+uid,giftType+":"+level,curDate)
							//充值任务
							dbService.app.rpc.db.task.updateTask(null,info.uid,"recharge",giftBagCfg[giftType][level].price,null)
							//奖励邮件
							dbService.app.rpc.db.mail.sendMail(null,uid,giftBagCfg[giftType][level].name,"您购买"+giftBagCfg[giftType][level].name+"获得以下奖励，祝您玩的开心！",giftBagCfg[giftType][level].award,function() {})
							local.messageFinish(info,true)
						}else{
							local.messageFinish(info,false,"今日已购买")
						}
					})
				}else{
					//限时礼包
					var notify = {
						cmd : "buyGiftBag",
						giftType : giftType,
						level : level
					}
					dbService.app.rpc.game.remote.sendByUid(null,uid,notify,function(){})
					//购买记录
					dbService.db.hincrby("game:giftBag:"+uid,giftType+":"+level+":count",1)
					//充值任务
					dbService.app.rpc.db.task.updateTask(null,info.uid,"recharge",giftBagCfg[giftType][level].price,null)
					//奖励邮件
					dbService.app.rpc.db.mail.sendMail(null,uid,giftBagCfg[giftType][level].name,"您购买"+giftBagCfg[giftType][level].name+"获得以下奖励，祝您玩的开心！",giftBagCfg[giftType][level].award,function() {})
					local.messageFinish(info,true)
				}
			}else{
				local.messageFinish(info,false,"argumentsError")
			}
		break
		case "deduction":
			//余额抵扣
			var value = info.value
			var uid = info.uid
			if(!uid || typeof(uid) !== "number" || !value || typeof(value) !== "number" || value < 0){
				local.messageFinish(info,false,"argumentsError")
				return
			}
			dbService.getItem(uid,103,function(data) {
				if(!data || data < value){
					local.messageFinish(info,false,"余额不足:"+value+"/"+data)
					return
				}else{
					dbService.addItemReason(uid,103,-value,"余额抵扣",function(flag) {
						local.messageFinish(info,flag)
					})
				}
			})
		break
		case "notify":
			//发公告
			if(info.content && typeof(info.content) == "string"){
				dbService.app.rpc.db.remote.updateNotify(null,info.content,1,function(flag) {
					if(flag){
						local.messageFinish(info,true)
					}else{
						local.messageFinish(info,false,"setError")
					}
				})
			}else{
				local.messageFinish(info,false,"argumentsError")
			}
		break
		default:
			local.messageFinish(info,false,"typeError")
	}
}
//处理完成
local.messageFinish = function(info,state,err) {
	if(state == true){
		info.state = true
	}else{
		info.state = false
	}
	if(err){
		info.err = err
	}
	if(state == false){
		local.messageError(info,err)
	}
	if(info.respond){
		local.messageRespond(info)
	}
}
//处理反馈
local.messageRespond = function(info) {
	db.rpush("backstageMessageRespond",JSON.stringify(info))
}
//错误信息
local.messageError = function(info,err) {
	if(err){
		info.err = err
	}
	db.rpush("backstageMessageError",JSON.stringify(info))
}
